import Vue from 'vue'
import VueRouter from 'vue-router'
import Navs from './nav.json'
import store from '../store';
import util from '../libs/util';

export const navs = Navs;

Vue.use(VueRouter);

const registerRoute = (groups) => {
    let routes = [];

    groups.map(group => {
        let groupItems = group.navItems;

        groupItems.map(nav => {
            try {
                routes.push({
                    path: `${nav.path}`,
                    component: resolve => require([`../pages${nav.path}.vue`], resolve),
                    name: nav.name,
                    meta: {
                        title: nav.title,
                        description: nav.description
                    }
                })
            } catch (e) {
                nav.disabled = true
            }
        })
    });

    return routes
};

const routes = registerRoute(Navs);

routes.push({
    path: '/',
    component: resolve => require(['../pages/user/profiles.vue'], resolve),
    name: '个人中心',
    meta: {
        title: '个人中心',
        description: ''
    }
});

routes.push({
    path: '*',
    component: resolve => require(['../pages/404.vue'], resolve),
    name: '404',
    meta: {
        title: '404 Not Found',
        description: ''
    }
});

const router = new VueRouter({
    base: '/',
    routes
});



router.beforeEach((to, from, next) => {
    store.commit('UPDATE_LOADING', true);
    console.log(to.fullPath, from.fullPath);

    // 判断登录状态
    util.isLogin();

    // 登录状态
    if (!store.state.user.user.hasOwnProperty('id')) { // 未登录
        if (util.oneOf(to.name, ['register', 'login', 'forgot-password', 'reset-password-mobile'])) {
            next();
        } else {
            store.commit('setBackUrl', to.fullPath);
            next({
                name: 'login'
            });
        }
    } else if (to.name == 'login' && store.state.user.user.hasOwnProperty('id')) {
        next({
            name: 'user-profiles'
        });
    } else {
        next();
    }
});

router.afterEach((to, from) => {
    store.commit('UPDATE_LOADING', false);
    document.title = to.meta.title
});

export default router